<?php
namespace catchAdmin\product\model;

use catchAdmin\product\model\search\ProductSearch;
use catcher\base\CatchModel;
use catcher\CatchAuth;
use think\facade\Db;
use catchAdmin\product\model\Pack as pack;

class Product extends CatchModel
{

    use ProductSearch;
    
    protected $name = 'db_product';
    protected $field = [
            'id', //
			'goods_id', // 商品编号
			'barcode', // 商品条形码
			'supplier_id', // 供应商编号
			'manufacturer_id', // 制造商编号
			'packing_id', // 包装编号
			'goods_name', // 商品名称
			'goods_Ename', // 商品英文名称
			'goods_Cname', // 商品中文名称
			'brand_id', // 品牌编号
			'brand_name', // 品牌名称
			'item_number_system', // 料号体系
			'company', // 基本单位
			'clean_heavy', // 单位净重
			'HSCODE', // 海关编码
			'relation_material', // 关联料号
			'describe', // 描述
			'tenant_id', // 商户id
            'creator_id', // 创建者ID
			'created_at', // 创建时间
			'updated_at', // 更新时间
			'deleted_at', // 删除状态，0未删除 >0 已删除
            'owner',//货主,
            'serial_number',//序列号
            'new_account_code',//客户代码
            'new_material_type',//物料型号
            'new_unit_of_measurement',//计量单位
            'new_declaration_elements',//申报要素
            'new_manual_number',//手册号
            'new_item_number',//项号
            'new_net_weight',//净重
            'new_pallet_size',//托盘尺寸
            'new_carton_size',//纸箱尺寸
            'new_gross_weight_per_support',//单托毛重
            'new_gross_weight_per_case',//单箱毛重
            'sku',//SKU物料型号+英文品名，中间用“/”连接
            '_ext_field_1',
            '_ext_field_2',
            '_ext_field_3',
            '_ext_field_4',
            '_ext_field_5'

    ];
    /**
     * 用户列表
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getList($tenant_id=0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['tenant_id','=',$tenant_id];
            $where[]=['deleted_at','=',0];
        }
        return $this->withoutField(['updated_at'], true)
            ->catchSearch()
            ->where($where)
            ->order($this->aliasField('id'), 'desc')
            ->paginate()
            ->each(function (&$item){
                $item['packing_id'] = $item['packing_id']?explode(',',$item['packing_id']):[];

                $item['supplier_name'] = Db::table('db_provider')
                    ->where(['id' => $item['supplier_id']])
                    ->value('account_name');
                $item['manufacturer_name'] = Db::table('db_provider')
                    ->where(['id' => $item['supplier_id']])
                    ->value('account_name');

                $item['supplier_id'] = (int)$item['supplier_id'];
                $item['manufacturer_id'] = (int)$item['manufacturer_id'];

                if(empty($item['brand_name'])){
                    $item['brand_name'] = Db::table('db_brand')
                        ->where(['brand_id' => $item['brand_id']])
                        ->value('brand_name');
                }

                $item['packing_name'] = Db::table('db_packing')
                    ->whereIn('packing_id' , $item['packing_id'])
                    ->field('unit_name,packing_num,layup_num')
                    ->select();
            });
    }

    /**
     *  无分页列表
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getAttrList($tenant_id=0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['tenant_id','=',$tenant_id];
        }
        return $this
            ->catchSearch()
            ->field('id,goods_id,goods_name,barcode,packing_id')
            ->where($where)
            ->order($this->aliasField('id'), 'desc')
            ->select();
    }
    /**
     * 商品对应的包装
     *
     * @time 2019年12月08日
     * @return array|\think\Paginator
     *@throws \think\db\exception\DbException
     */
    public function getGoodsPacking($tenant_id=0)
    {
        $where = [];
        if(!empty($tenant_id)){
            $where[] = ['g.tenant_id','=',$tenant_id];
        }
        return $this->catchSearch()
                ->alias('g')
                ->where($where)
                ->order('g.id', 'desc')
                ->field('g.goods_id,g.goods_name,packing_id')
                ->select()
                ->each(function (&$item){
//                    $item['children'] = Db::table('db_packing')
//                        ->field('packing_id,unit_name,packing_num')
//                        ->whereIn('packing_id',$item['packing_id'])
//                        ->select();
                    $item['children'] = pack::field('packing_id,unit_name,packing_num')
                        ->whereIn('packing_id',$item['packing_id'])
                        ->select();
                });
    }

    //序列号
    public static function onBeforeInsert($product){
        //查询数量
//        $count =  Db::table('db_product')->where('tenant_id',$product->tenant_id)->count();
//        //公司代码
//        $co_code = Db::table('users')->where('id',$product->tenant_id)->value('co_code');
//
//        if( !empty($co_code) ){
//            $head = strtoupper($co_code)  . "G";
//            $product->serial_number = $head . str_pad($count + 1,5,'0',STR_PAD_LEFT);
//        }else{//无锡公司
//            $product->serial_number = "G" . str_pad($count + 1,5,'0',STR_PAD_LEFT);
//        }
    }

    public function getTotalProductNumber(){
        $user = (new CatchAuth)->user();

        $where = [
            ['deleted_at','=',0],
        ];

        if($user['type'] !== 1) {//普通商户
            $where[] = ['tenant_id','=',$user['tenant_id']];
        }

        $count = $this->where($where)->count();
        return $count;
    }
}
